package com.java110.mall.chain.partner.adapter.hibo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.core.factory.AuthenticationFactory;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.product.ProductSpecValueDto;
import com.java110.dto.shop.ShopDto;
import com.java110.dto.storeOrder.StoreOrderDto;
import com.java110.dto.storeOrder.StoreOrderReturnPayDto;
import com.java110.dto.storeOrder.StoreOrderCartDto;
import com.java110.dto.storeOrder.StoreOrderCartEventDto;
import com.java110.dto.storeOrder.StoreOrderCartReturnDto;
import com.java110.dto.user.UserDto;
import com.java110.dto.user.UserAddressDto;
import com.java110.intf.cart.*;
import com.java110.intf.chain.IPartnerOrderV1InnerServiceSMO;
import com.java110.intf.chain.IPartnerPoolValueV1InnerServiceSMO;
import com.java110.intf.goods.IProductSpecValueInnerServiceSMO;
import com.java110.intf.shop.IShopInnerServiceSMO;
import com.java110.intf.user.IUserAddressInnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.mall.chain.partner.IPartnerOrderVerificationAdapter;
import com.java110.po.partnerAdapt.PartnerOrderPo;
import com.java110.po.storeOrder.StoreOrderCartPo;
import com.java110.po.storeOrder.StoreOrderCartEventPo;
import com.java110.po.storeOrder.StoreOrderCartReturnPo;
import com.java110.po.storeOrder.StoreOrderCartReturnEventPo;
import com.java110.po.user.UserPo;
import com.java110.po.user.UserAddressPo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.ListUtil;
import com.java110.utils.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service("orderVerifactionHiboosAdaperImpl")
public class OrderVerifactionHiboosAdaperImpl implements IPartnerOrderVerificationAdapter {

    @Autowired
    private IShopInnerServiceSMO shopInnerServiceSMOImpl;

    @Autowired
    private IUnifiedOrderInnerServiceSMO unifiedOrderInnerServiceSMOImpl;

    @Autowired
    private IUserAddressInnerServiceSMO userAddressInnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMOImpl;

    @Autowired
    private IPartnerPoolValueV1InnerServiceSMO partnerPoolValueV1InnerServiceSMOImpl;

    @Autowired
    private IProductSpecValueInnerServiceSMO productSpecValueInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartInnerServiceSMO storeOrderCartInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderInnerServiceSMO storeOrderInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartReturnInnerServiceSMO storeOrderCartReturnInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartReturnEventInnerServiceSMO storeOrderCartReturnEventInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartEventInnerServiceSMO storeOrderCartEventInnerServiceSMOImpl;


    @Autowired
    private IPartnerOrderV1InnerServiceSMO partnerOrderV1InnerServiceSMOImpl;

    @Override
    public ResponseEntity<String> createOrder(JSONObject reqJson) {

        Assert.hasKeyAndValue(reqJson, "outStationNo", "未包含商家编码");

        JSONArray productList = reqJson.getJSONArray("productList");

        if (ListUtil.isNull(productList)) {
            throw new CmdException("未包含商品");
        }

        String shopId = reqJson.getString("shopId");

        ShopDto shopDto = new ShopDto();
        shopDto.setShopId(reqJson.getString("shopId"));
        List<ShopDto> shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);
        if (ListUtil.isNull(shopDtos)) {
            throw new CmdException("店铺不存在");
        }

        String recipientPhone = reqJson.getString("recipientPhone");
        String recipientName = reqJson.getString("recipientName");
        String recipientAddress = reqJson.getString("recipientAddress");
        if(StringUtil.isEmpty(recipientPhone)){
            recipientPhone = shopDtos.get(0).getReturnLink();
            reqJson.put("recipientPhone",recipientPhone);
        }

        if(StringUtil.isEmpty(recipientName)){
            recipientName = shopDtos.get(0).getReturnPerson();
            reqJson.put("recipientName",recipientName);
        }

        if(StringUtil.isEmpty(recipientAddress)){
            recipientAddress = shopDtos.get(0).getReturnAddress();
            reqJson.put("recipientAddress",recipientAddress);
        }


        //todo 保存收货地址信息
        UserDto userDto = new UserDto();
        userDto.setTel(recipientPhone);
        userDto.setLevelCd(UserDto.LEVEL_CD_MALL);
        List<UserDto> userDtos = userV1InnerServiceSMOImpl.queryUsers(userDto);


        if (ListUtil.isNull(userDtos)) {
            userDtos = saveUser(recipientName, recipientPhone);
        }


        UserAddressDto userAddressDto = new UserAddressDto();
        userAddressDto.setTel(reqJson.getString("recipientPhone"));
        List<UserAddressDto> userAddressDtos = userAddressInnerServiceSMOImpl.queryUserAddresss(userAddressDto);

        if (ListUtil.isNull(userAddressDtos)) {
            userAddressDtos = saveUserAddress(userDtos.get(0),
                    shopDtos.get(0),
                    reqJson.getString("recipientName"),
                    reqJson.getString("recipientPhone"),
                    reqJson.getString("recipientAddress"));
        }


        /**
         * {
         * 					"storeOrder": {
         * 						remark: _that.remark,
         * 						personId: _that.vc.getCurrentUser().userId,
         * 						personName: _that.vc.getCurrentUser().userName,
         * 						userId: _that.vc.getCurrentUser().userId,
         *                                        },
         * 					"storeOrderCarts": [
         *                                {
         * 							"cateType": "1",
         * 							"productId": item.productId,
         * 							"prodName": item.prodName,
         * 							"valueId": item.valueId,
         * 							"goodsNum": item.goodsNum,
         * 							"extProdId": item.extProdId,
         * 							"extValueId": item.extValueId,
         * 							"suType": item.suType,
         * 							"csId": item.csId,
         * 							"shopId": _that.shopId,
         * 							"cartType": param.CART_TYPE.SHOP
         *                        }	],
         * 					"shopId": _that.shopId,
         * 					"vipUsers": _that.orderInfo.vipUserDto,
         * 					"addressId": _address.addressId,
         *            }
         */

        JSONObject param = new JSONObject();
        param.put("shopId", shopId);
        //storeOrder.put("vipUsers",new JSONObject());
        param.put("addressId", userAddressDtos.get(0).getAddressId());
        JSONObject storeOrder = new JSONObject();
        storeOrder.put("remark", shopId);
        storeOrder.put("personId", userDtos.get(0).getUserId());
        storeOrder.put("personName", userDtos.get(0).getName());
        storeOrder.put("userId", userDtos.get(0).getUserId());

        JSONArray storeOrderCarts = new JSONArray();


        JSONObject product = null;
        JSONObject storeOrderCart = null;

        /**
         * "cateType": "1",
         * 						"productId": item.productId,
         * 						"prodName": item.prodName,
         * 						"valueId": item.valueId,
         * 						"goodsNum": item.goodsNum,
         * 						"extProdId": item.extProdId,
         * 						"extValueId": item.extValueId,
         * 						"suType": item.suType,
         * 						"csId": item.csId,
         * 						"shopId": _that.shopId,
         * 						"cartType": param.CART_TYPE.SHOP
         */
        for (int pIndex = 0; pIndex < productList.size(); pIndex++) {
            product = productList.getJSONObject(pIndex);


            ProductSpecValueDto productSpecValueDto = new ProductSpecValueDto();
            productSpecValueDto.setValueId(product.getString("outSkuId"));
            productSpecValueDto.setShopId(shopId);
            List<ProductSpecValueDto> productSpecValueDtos = productSpecValueInnerServiceSMOImpl.queryProductSpecValues(productSpecValueDto);
            if (ListUtil.isNull(productSpecValueDtos)) {
                throw new CmdException("商品不存在");
            }

            storeOrderCart = new JSONObject();
            storeOrderCart.put("cateType", "1");
            storeOrderCart.put("productId", productSpecValueDtos.get(0).getProductId());
            storeOrderCart.put("prodName", productSpecValueDtos.get(0).getProdName());
            storeOrderCart.put("valueId", product.getString("outSkuId"));
            storeOrderCart.put("goodsNum", product.getIntValue("skuCount"));
            storeOrderCart.put("extProdId", "1");
            storeOrderCart.put("extValueId", "1");
            storeOrderCart.put("suType", "1");
            storeOrderCart.put("csId", "1");
            storeOrderCart.put("shopId", shopId);
            storeOrderCart.put("cartType", "3306");

            storeOrderCarts.add(storeOrderCart);
        }


        param.put("storeOrder", storeOrder);
        param.put("storeOrderCarts", storeOrderCarts);
        param.put("appId",reqJson.getString("appId"));

        StoreOrderReturnPayDto storeOrderReturnPayDto = unifiedOrderInnerServiceSMOImpl.unifiedOrder(param);
        JSONObject paramNotify = new JSONObject();
        paramNotify.put("orderId", storeOrderReturnPayDto.getOrderId());
        paramNotify.put("payOrderId", reqJson.getString("channelOrderId"));
        paramNotify.put("extOrderId", reqJson.getString("channelOrderId"));
        ResponseEntity<String> responseEntity = unifiedOrderInnerServiceSMOImpl.payNotifyOrder(paramNotify);

        //todo 保存合作订单

        long totalPrice = reqJson.getLongValue("totalPrice");

        PartnerOrderPo partnerOrderPo = new PartnerOrderPo();
        partnerOrderPo.setPersonName(userDtos.get(0).getName());
        partnerOrderPo.setOrderId(storeOrderReturnPayDto.getOrderId());
        partnerOrderPo.setTotalPrice(totalPrice / 100.00 + "");
        partnerOrderPo.setChannel(reqJson.getString("channel"));
        partnerOrderPo.setRemark("");
        partnerOrderPo.setShopId(shopId);
        partnerOrderPo.setState("C");
        partnerOrderPo.setPersonTel(userDtos.get(0).getTel());
        partnerOrderPo.setTransactionId(reqJson.getString("transactionId"));
        partnerOrderPo.setPpId(reqJson.getString("ppId"));
        partnerOrderPo.setRefund("N");

        partnerOrderV1InnerServiceSMOImpl.savePartnerOrder(partnerOrderPo);

        JSONObject paramOut = new JSONObject();
        paramOut.put("code", 0);
        paramOut.put("msg", "成功");
        paramOut.put("success", true);
        paramOut.put("result", new JSONArray());
        return new ResponseEntity(paramOut.toJSONString(), HttpStatus.OK);
    }

    private List<UserAddressDto> saveUserAddress(UserDto userDto, ShopDto shopDto, String recipientName, String recipientPhone, String recipientAddress) {

        if (StringUtil.isEmpty(recipientAddress)) {
            recipientAddress = "无";
        }
        UserAddressPo userAddressPo = new UserAddressPo();
        userAddressPo.setAreaCode(shopDto.getAreaCode());
        userAddressPo.setIsDefault("T");
        userAddressPo.setAddress(recipientAddress);
        userAddressPo.setTel(recipientPhone);

        userAddressPo.setUserId(userDto.getUserId());
        userAddressPo.setUsername(recipientName);
        userAddressPo.setbId("-1");
        userAddressPo.setPostalCode("无");

        userAddressPo.setAddressId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_addressId));
        userAddressInnerServiceSMOImpl.saveUserAddress(userAddressPo);

        UserAddressDto userAddressDto = new UserAddressDto();
        userAddressDto.setTel(recipientPhone);
        List<UserAddressDto> userAddressDtos = userAddressInnerServiceSMOImpl.queryUserAddresss(userAddressDto);
        return userAddressDtos;
    }

    private List<UserDto> saveUser(String recipientName, String recipientPhone) {

        UserPo userPo = new UserPo();
        userPo.setTel(recipientPhone);
        userPo.setName(recipientName);
        userPo.setAddress("无");
        userPo.setUserId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_userId));
        userPo.setScore("0");
        userPo.setAge("1");
        userPo.setEmail("无");
        userPo.setLevelCd(UserDto.LEVEL_CD_MALL);
        userPo.setSex("1");
        userPo.setPassword(AuthenticationFactory.passwdMd5(recipientPhone));
        userPo.setbId("-1");
        int flag = userV1InnerServiceSMOImpl.saveUser(userPo);
        if (flag < 1) {
            throw new CmdException("注册失败");
        }
        UserDto userDto = new UserDto();
        userDto.setTel(recipientPhone);
        userDto.setLevelCd(UserDto.LEVEL_CD_MALL);
        List<UserDto> userDtos = userV1InnerServiceSMOImpl.queryUsers(userDto);
        return userDtos;
    }

    @Override
    public ResponseEntity<String> refundOrder(JSONObject reqJson) {


        String channelOrderId = reqJson.getString("channelOrderId");

        String afterOrderId = reqJson.getString("afterOrderId");

        String shopId = reqJson.getString("shopId");

        ShopDto shopDto = new ShopDto();
        shopDto.setShopId(reqJson.getString("shopId"));
        List<ShopDto> shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);
        if (ListUtil.isNull(shopDtos)) {
            throw new CmdException("店铺不存在");
        }


        StoreOrderDto storeOrderDto = new StoreOrderDto();
        storeOrderDto.setExtOrderId(channelOrderId);
        List<StoreOrderDto> storeOrderDtos = storeOrderInnerServiceSMOImpl.queryOnlyStoreOrders(storeOrderDto);

        if (ListUtil.isNull(storeOrderDtos)) {
            throw new CmdException("订单不存在");
        }

        String orderId = storeOrderDtos.get(0).getOrderId();
        String personId = storeOrderDtos.get(0).getPersonId();
        String returnReason = "海博平台退货：退货单号=" + afterOrderId;

        JSONArray productList = reqJson.getJSONArray("productList");

        JSONObject product = null;
        for (int pIndex = 0; pIndex < productList.size(); pIndex++) {
            product = productList.getJSONObject(pIndex);
            //查询
            StoreOrderCartDto storeOrderCartDto = new StoreOrderCartDto();
            storeOrderCartDto.setValueId(product.getString("outSkuId"));
            storeOrderCartDto.setShopId(shopId);
            storeOrderCartDto.setStates(new String[]{StoreOrderCartDto.STATE_SENDING,
                    StoreOrderCartDto.STATE_WAIT_SEND,
                    StoreOrderCartDto.STATE_FINISH,
                    StoreOrderCartDto.STATE_WAIT_SERV_DROP_IN,
                    StoreOrderCartDto.STATE_WAIT_SERV_WAIT_PAY,
                    StoreOrderCartDto.STATE_WAIT_SERV_R,
                    StoreOrderCartDto.STATE_WAIT_REPAIR,
            });

            List<StoreOrderCartDto> storeOrderCartDtos = storeOrderCartInnerServiceSMOImpl.queryStoreOrderCarts(storeOrderCartDto);

            Assert.listOnlyOne(storeOrderCartDtos, "当前不符合退货条件");
            StoreOrderCartReturnPo storeOrderCartReturnPo = new StoreOrderCartReturnPo();
            storeOrderCartReturnPo.setOrderId(orderId);
            storeOrderCartReturnPo.setReturnReason(returnReason);
            storeOrderCartReturnPo.setCartId(storeOrderCartDtos.get(0).getCartId());
            storeOrderCartReturnPo.setPersonId(personId);
            storeOrderCartReturnPo.setStoreId(shopDto.getStoreId());
            storeOrderCartReturnPo.setShopId(shopId);
            storeOrderCartReturnPo.setMessage("待审核");

            storeOrderCartReturnPo.setReturnId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_returnId));
            if (StringUtil.isEmpty(storeOrderCartReturnPo.getReturnCartNum())) {
                storeOrderCartReturnPo.setReturnCartNum(product.getString("skuCount"));
            }

            long payPrice = product.getLong("payValue");
            BigDecimal payPriceDec = new BigDecimal(payPrice);
            payPriceDec = payPriceDec.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
            storeOrderCartReturnPo.setReturnPayPrice(payPriceDec.doubleValue() + "");
            storeOrderCartReturnPo.setReturnType(StoreOrderCartReturnDto.RETURN_TYPE_CART);
            storeOrderCartReturnPo.setState(StoreOrderCartReturnDto.STATE_APPLY);
            storeOrderCartReturnPo.setStoreId(storeOrderCartDtos.get(0).getStoreId());
            int flag = storeOrderCartReturnInnerServiceSMOImpl.saveStoreOrderCartReturn(storeOrderCartReturnPo);

            if (flag < 1) {
                throw new IllegalArgumentException("保存失败");
            }

            StoreOrderCartReturnEventPo storeOrderCartReturnEventPo = new StoreOrderCartReturnEventPo();
            storeOrderCartReturnEventPo.setEventId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId));
            storeOrderCartReturnEventPo.setEventMsg("用户申请退货");
            storeOrderCartReturnEventPo.setEventObjId(storeOrderCartReturnPo.getPersonId());
            storeOrderCartReturnEventPo.setEventObjType("U");//用户申请
            storeOrderCartReturnEventPo.setReturnId(storeOrderCartReturnPo.getReturnId());
            storeOrderCartReturnEventPo.setStoreId(storeOrderCartReturnPo.getStoreId());
            storeOrderCartReturnEventPo.setShopId(storeOrderCartReturnPo.getShopId());

            flag = storeOrderCartReturnEventInnerServiceSMOImpl.saveStoreOrderCartReturnEvent(storeOrderCartReturnEventPo);
            if (flag < 1) {
                throw new IllegalArgumentException("保存失败");
            }

            //加入订单事件
            StoreOrderCartEventPo storeOrderCartEventPo = new StoreOrderCartEventPo();
            storeOrderCartEventPo.setEventId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId));
            storeOrderCartEventPo.setEventMsg("用户申请退货");
            storeOrderCartEventPo.setEventObjId(storeOrderCartReturnPo.getPersonId());
            storeOrderCartEventPo.setEventObjType("U");//用户申请
            storeOrderCartEventPo.setEventType(StoreOrderCartEventDto.EVENT_TYPE_COMMON);
            storeOrderCartEventPo.setOrderId(storeOrderCartDtos.get(0).getOrderId());
            storeOrderCartEventPo.setCartId(storeOrderCartDtos.get(0).getCartId());
            storeOrderCartEventPo.setShopId(storeOrderCartReturnPo.getShopId());

            flag = storeOrderCartEventInnerServiceSMOImpl.saveStoreOrderCartEvent(storeOrderCartEventPo);
            if (flag < 1) {
                throw new IllegalArgumentException("保存失败");
            }

            StoreOrderCartPo storeOrderCartPo = new StoreOrderCartPo();
            storeOrderCartPo.setCartId(storeOrderCartDtos.get(0).getCartId());
            storeOrderCartPo.setState(StoreOrderCartDto.STATE_REQ_RETURN);
            storeOrderCartPo.setStoreId(storeOrderCartDtos.get(0).getStoreId());
            storeOrderCartPo.setShopId(storeOrderCartReturnPo.getShopId());
            flag = storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);
            if (flag < 1) {
                throw new IllegalArgumentException("保存失败");
            }
        }
        long totalPrice = reqJson.getLongValue("totalPrice");

        //todo 保存收货地址信息
        UserDto userDto = new UserDto();
        userDto.setUserId(storeOrderDtos.get(0).getPersonId());
        userDto.setLevelCd(UserDto.LEVEL_CD_MALL);
        List<UserDto> userDtos = userV1InnerServiceSMOImpl.queryUsers(userDto);


        if (ListUtil.isNull(userDtos)) {
            userDtos = saveUser(reqJson.getString("recipientName"), reqJson.getString("recipientPhone"));
        }

        PartnerOrderPo partnerOrderPo = new PartnerOrderPo();
        partnerOrderPo.setPersonName(storeOrderDtos.get(0).getPersonName());
        partnerOrderPo.setOrderId(storeOrderDtos.get(0).getOrderId());
        partnerOrderPo.setTotalPrice(totalPrice / 100.00 + "");
        partnerOrderPo.setChannel(reqJson.getString("channel"));
        partnerOrderPo.setRemark("");
        partnerOrderPo.setShopId(shopId);
        partnerOrderPo.setState("C");
        partnerOrderPo.setPersonTel(userDtos.get(0).getTel());
        partnerOrderPo.setTransactionId(reqJson.getString("transactionId"));
        partnerOrderPo.setPpId(reqJson.getString("ppId"));
        partnerOrderPo.setRefund("Y");

        partnerOrderV1InnerServiceSMOImpl.savePartnerOrder(partnerOrderPo);

        JSONObject paramOut = new JSONObject();
        paramOut.put("code", 0);
        paramOut.put("msg", "成功");
        paramOut.put("success", true);
        paramOut.put("result", new JSONArray());
        return new ResponseEntity(paramOut.toJSONString(), HttpStatus.OK);
    }
}
